package com.tanhua.service;

import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.User;
import org.apache.commons.codec.cli.Digest;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 */
@Service
public class UserService {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private UserApi userApi;
    /**
     * 发送短信验证码
     *
     * @param phone
     */
    public void sendCode(String phone) {
        //1. 生成随机验证码
        //String code = RandomStringUtils.randomNumeric(6);
        String code="123456";
        //2. 调用阿里云发送验证码
        //smsTemplate.sendSms(phone, code);
        //3. 将验证码保存到redis
        redisTemplate.opsForValue().set("CHECK_CODE_" + phone, code, Duration.ofMinutes(5));
    }

    /**
     * 验证登录
     * @param phone
     * @param code
     * @return
     */
    public Map loginVerification(String phone, String code) {
//        从redis获取验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);
//        判断验证码是否合法（验证码是否存在，是否和输入的一致）
        if (StringUtils.isEmpty(redisCode)||!redisCode.equals(code)){
            throw new RuntimeException("验证码错误");
        }
//        删除redis中的验证码
         redisTemplate.delete("CHECK_CODE_" + phone);
//        根据手机号查询用户
        User user = userApi.findByMobile(phone);
        boolean isNew=false;
//        判断用户是否存在，若不存在添加新用户
        if (user==null){
            user = new User();
            user.setMobile(phone);
            //user.setCreated(new Date());
            //user.setUpdated(new Date());
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew=true;

        }
//         通过JWT生成token(存入id和手机号码)
        Map tokenMap=new HashMap();
        tokenMap.put("id",user.getId());
        tokenMap.put("mobile",phone);
        String token = JwtUtils.getToken(tokenMap);
//        构造数据响应
        Map retMap=new HashMap();
        retMap.put("token",token);
        retMap.put("isNew",isNew);
        return retMap;

    }
}